<script setup>
import { articleEditCategoryService, articleAddCategoryService } from '@/api/article'
import { ref } from 'vue'
const dialogVisible = ref(false)
const formRef = ref({})
// 根据传入的值，决定展示的是添加还是编辑
// 添加 {}  编辑{xxx信息}

// 表单
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
// 校验规则
const rules = {
  cate_name: [
    { require: true, message: '请输入分类名称', trigger: 'blur' },
    { pattern: /^\S{1,15}$/, message: '分类名必须是1-10位的非空字符', trigger: 'blur' }
  ],
  cate_alias: [
    { require: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
}
// 对外暴露的open函数
const open = (row) => {
  formModel.value = row
  dialogVisible.value = true
}
defineExpose({
  open
})
// 子传父，通知父组件，刷新分类列表
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate
  if (formModel.value.id) {
    await articleEditCategoryService(formModel.value)
  } else {
    await articleAddCategoryService(formModel.value)
  }
  ElMessage.success(`${formModel.value.id ? '修改成功' : '添加成功'}`)
  dialogVisible.value = false
  emit('success')
}
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="formModel.id ? '编辑分类' : '添加分类'" width="500">
    <el-form :model="formModel" :rules="rules" ref="formRef">
      <el-form-item label="分类名称" width="100" style="padding: 0 30px" prop="cate_name">
        <el-input v-model="formModel.cate_name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="分类别名" width="100" style="padding: 0 30px" prop="cate_alias">
        <el-input v-model="formModel.cate_alias" placeholder="请输入分类别名" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
